﻿// Decompiled with JetBrains decompiler
// Type: TaleWorlds.CampaignSystem.Issues.ArtisanCantSellProductsAtAFairPriceIssueBehavior
// Assembly: TaleWorlds.CampaignSystem, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: E85F8C15-4DF6-4E9C-A58A-29177E40D07A
// Assembly location: D:\steam\steamapps\common\Mount & Blade II Bannerlord\bin\Win64_Shipping_Client\TaleWorlds.CampaignSystem.dll

using Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using TaleWorlds.CampaignSystem.Actions;
using TaleWorlds.CampaignSystem.CharacterDevelopment;
using TaleWorlds.CampaignSystem.Conversation;
using TaleWorlds.CampaignSystem.GameMenus;
using TaleWorlds.CampaignSystem.GameState;
using TaleWorlds.CampaignSystem.Party;
using TaleWorlds.CampaignSystem.Roster;
using TaleWorlds.CampaignSystem.Settlements;
using TaleWorlds.Core;
using TaleWorlds.Library;
using TaleWorlds.Localization;
using TaleWorlds.ObjectSystem;
using TaleWorlds.SaveSystem;

#nullable disable
namespace TaleWorlds.CampaignSystem.Issues
{
  public class ArtisanCantSellProductsAtAFairPriceIssueBehavior : CampaignBehaviorBase
  {
    private const float MaxDistanceForSettlementSelection = 150f;
    private const IssueBase.IssueFrequency ArtisanCantSellProductsAtAFairPriceIssueFrequency = IssueBase.IssueFrequency.Common;

    public override void RegisterEvents()
    {
      CampaignEvents.OnCheckForIssueEvent.AddNonSerializedListener((object) this, new Action<Hero>(this.OnCheckForIssue));
    }

    public void OnCheckForIssue(Hero hero)
    {
      if (this.ConditionsHold(hero))
        Campaign.Current.IssueManager.AddPotentialIssueData(hero, new PotentialIssueData(new PotentialIssueData.StartIssueDelegate(this.OnStartIssue), typeof (ArtisanCantSellProductsAtAFairPriceIssueBehavior.ArtisanCantSellProductsAtAFairPriceIssue), IssueBase.IssueFrequency.Common));
      else
        Campaign.Current.IssueManager.AddPotentialIssueData(hero, new PotentialIssueData(typeof (ArtisanCantSellProductsAtAFairPriceIssueBehavior.ArtisanCantSellProductsAtAFairPriceIssue), IssueBase.IssueFrequency.Common));
    }

    private bool ConditionsHold(Hero issueGiver)
    {
      return issueGiver.IsArtisan && ArtisanCantSellProductsAtAFairPriceIssueBehavior.SelectCounterOfferHero(issueGiver) != null && ArtisanCantSellProductsAtAFairPriceIssueBehavior.SelectTargetSettlement(issueGiver) != null;
    }

    private static Hero SelectCounterOfferHero(Hero issueGiver)
    {
      return issueGiver.CurrentSettlement.Notables.FirstOrDefault<Hero>((Func<Hero, bool>) (x => x.CharacterObject.IsHero && x.CanHaveQuestsOrIssues() && x.CharacterObject.HeroObject != issueGiver && x.CharacterObject.HeroObject.IsMerchant));
    }

    private static Settlement SelectTargetSettlement(Hero issueGiver)
    {
      Settlement issueSettlement = issueGiver.CurrentSettlement;
      return SettlementHelper.FindRandomSettlement((Func<Settlement, bool>) (x => x.IsTown && x != issueSettlement && x.Notables.Any<Hero>((Func<Hero, bool>) (y => y.CanHaveQuestsOrIssues())) && Campaign.Current.Models.MapDistanceModel.GetDistance(x, issueSettlement, 150f, out float _)));
    }

    private IssueBase OnStartIssue(in PotentialIssueData pid, Hero issueOwner)
    {
      return (IssueBase) new ArtisanCantSellProductsAtAFairPriceIssueBehavior.ArtisanCantSellProductsAtAFairPriceIssue(issueOwner);
    }

    public override void SyncData(IDataStore dataStore)
    {
    }

    public class ArtisanCantSellProductsAtAFairPriceIssue : IssueBase
    {
      private const int BaseRewardGold = 500;
      private const int IssueDuration = 30;
      private const int QuestTimeLimit = 18;
      private const int RequiredSkillLevelForCompanion = 120;
      [CachedData]
      private readonly MBList<string> _possibleDeliveryItems;
      [SaveableField(10)]
      private ItemObject _rawMaterialsToBeDelivered;
      [SaveableField(20)]
      private Settlement _targetSettlement;
      [SaveableField(40)]
      private Hero _targetHero;

      internal static void AutoGeneratedStaticCollectObjectsArtisanCantSellProductsAtAFairPriceIssue(
        object o,
        List<object> collectedObjects)
      {
        ((MBObjectBase) o).AutoGeneratedInstanceCollectObjects(collectedObjects);
      }

      protected override void AutoGeneratedInstanceCollectObjects(List<object> collectedObjects)
      {
        base.AutoGeneratedInstanceCollectObjects(collectedObjects);
        collectedObjects.Add((object) this._rawMaterialsToBeDelivered);
        collectedObjects.Add((object) this._targetSettlement);
        collectedObjects.Add((object) this._targetHero);
        collectedObjects.Add((object) this.CounterOfferHero);
      }

      internal static object AutoGeneratedGetMemberValueCounterOfferHero(object o)
      {
        return (object) ((IssueBase) o).CounterOfferHero;
      }

      internal static object AutoGeneratedGetMemberValue_rawMaterialsToBeDelivered(object o)
      {
        return (object) ((ArtisanCantSellProductsAtAFairPriceIssueBehavior.ArtisanCantSellProductsAtAFairPriceIssue) o)._rawMaterialsToBeDelivered;
      }

      internal static object AutoGeneratedGetMemberValue_targetSettlement(object o)
      {
        return (object) ((ArtisanCantSellProductsAtAFairPriceIssueBehavior.ArtisanCantSellProductsAtAFairPriceIssue) o)._targetSettlement;
      }

      internal static object AutoGeneratedGetMemberValue_targetHero(object o)
      {
        return (object) ((ArtisanCantSellProductsAtAFairPriceIssueBehavior.ArtisanCantSellProductsAtAFairPriceIssue) o)._targetHero;
      }

      public override IssueBase.AlternativeSolutionScaleFlag AlternativeSolutionScaleFlags
      {
        get => IssueBase.AlternativeSolutionScaleFlag.Duration;
      }

      [SaveableProperty(30)]
      public override Hero CounterOfferHero { get; protected set; }

      private int RawMaterialCountToBeDelivered
      {
        get => (int) (60.0 * (double) this.IssueDifficultyMultiplier);
      }

      public override int AlternativeSolutionBaseNeededMenCount
      {
        get => 3 + MathF.Ceiling(6f * this.IssueDifficultyMultiplier);
      }

      protected override int AlternativeSolutionBaseDurationInDaysInternal
      {
        get => 3 + MathF.Ceiling(5f * this.IssueDifficultyMultiplier);
      }

      protected override int RewardGold
      {
        get => (int) (500.0 + 1500.0 * (double) this.IssueDifficultyMultiplier);
      }

      public override int NeededInfluenceForLordSolution
      {
        get => 10 + MathF.Round(40f * this.IssueDifficultyMultiplier);
      }

      protected override TextObject AlternativeSolutionStartLog
      {
        get
        {
          TextObject parent = new TextObject("{=4M6jlZVa}{ISSUE_GIVER.LINK} an artisan from {ISSUE_GIVER_SETTLEMENT} has complained to you about not being able to sell their goods at the price they want because of local laws. {?ISSUE_GIVER.GENDER}She{?}He{\\?} will pay {REWARD}{GOLD_ICON} for you to take the goods to another town. You have tasked {COMPANION.LINK} and {ALTERNATIVE_SOLUTION_TROOP_COUNT} men to smuggle {?ISSUE_GIVER.GENDER}her{?}his{\\?} goods to a “friend” in {TARGET_TOWN}. They will return to you in {RETURN_DAYS} days with a sizable sum of {REWARD}{GOLD_ICON}.");
          StringHelpers.SetCharacterProperties("ISSUE_GIVER", this.IssueOwner.CharacterObject, parent);
          StringHelpers.SetCharacterProperties("COMPANION", this.AlternativeSolutionHero.CharacterObject, parent);
          parent.SetTextVariable("ISSUE_GIVER_SETTLEMENT", this.IssueOwner.CurrentSettlement.EncyclopediaLinkWithName);
          parent.SetTextVariable("TARGET_TOWN", this._targetSettlement.EncyclopediaLinkWithName);
          parent.SetTextVariable("ALTERNATIVE_SOLUTION_TROOP_COUNT", this.AlternativeSolutionSentTroops.TotalManCount - 1);
          parent.SetTextVariable("RETURN_DAYS", this.GetTotalAlternativeSolutionDurationInDays());
          parent.SetTextVariable("REWARD", this.RewardGold);
          parent.SetTextVariable("GOLD_ICON", "{=!}<img src=\"General\\Icons\\Coin@2x\" extend=\"8\">");
          return parent;
        }
      }

      protected override int CompanionSkillRewardXP
      {
        get => (int) (400.0 + 1700.0 * (double) this.IssueDifficultyMultiplier);
      }

      public override bool IsThereAlternativeSolution => true;

      public override bool IsThereLordSolution => true;

      public override TextObject IssueBriefByIssueGiver
      {
        get
        {
          return new TextObject("{=Vg7Ftrdl}You might say that... I work from dawn to late into the night but even so I can barely put bread on the table. Why's that? Because I can't sell my product at a fair price. The law says that I can only sell to local merchants, and at a fixed rate too, so that even when other prices are high I'm still making the same.[if:convo_annoyed]");
        }
      }

      public override TextObject IssueAcceptByPlayer
      {
        get => new TextObject("{=ioF9aJBJ}How can I help?");
      }

      public override TextObject IssueQuestSolutionExplanationByIssueGiver
      {
        get
        {
          TextObject parent = new TextObject("{=bOyjQ4yr}If you can deliver {REQUESTED_AMOUNT} {.%}{?(REQUESTED_AMOUNT > 1)}{PLURAL(RAW_MATERIALS)}{?}{RAW_MATERIALS}{\\?}{.%} to my contact {TARGET_HERO.LINK}, who you can find in {TARGET_SETTLEMENT}, that would help me survive for a time. The merchants of the town could be furious and lodge legal complaints of course, but hopefully you won't have to deal with that part.");
          StringHelpers.SetCharacterProperties("TARGET_HERO", this._targetHero.CharacterObject, parent);
          parent.SetTextVariable("REQUESTED_AMOUNT", this.RawMaterialCountToBeDelivered);
          parent.SetTextVariable("RAW_MATERIALS", this._rawMaterialsToBeDelivered.Name);
          parent.SetTextVariable("TARGET_SETTLEMENT", this._targetSettlement.EncyclopediaLinkWithName);
          return parent;
        }
      }

      public override TextObject IssueAlternativeSolutionExplanationByIssueGiver
      {
        get
        {
          TextObject explanationByIssueGiver = new TextObject("{=Gzx35bRY}If you aren't going towards {TARGET_SETTLEMENT}, maybe you could have some of your men take my goods and bring back the profit? It shouldn't take more than {ALTERNATIVE_SOLUTION_MEN_AMOUNT} men and one of your trusted lieutenants with decent grasp of trade. They can go and be back in about {RETURN_DAYS} days.[if:convo_annoyed]");
          explanationByIssueGiver.SetTextVariable("TARGET_SETTLEMENT", this._targetSettlement.EncyclopediaLinkWithName);
          explanationByIssueGiver.SetTextVariable("ALTERNATIVE_SOLUTION_MEN_AMOUNT", this.GetTotalAlternativeSolutionNeededMenCount());
          explanationByIssueGiver.SetTextVariable("RETURN_DAYS", this.GetTotalAlternativeSolutionDurationInDays());
          return explanationByIssueGiver;
        }
      }

      public override TextObject IssueLordSolutionExplanationByIssueGiver
      {
        get
        {
          TextObject parent = new TextObject("{=tgj9BuCL}You could change this law, my {?PLAYER.GENDER}lady{?}lord{\\?}. All of us would be grateful. and we're willing to donate {REWARD}{GOLD_ICON} to show our thanks...");
          StringHelpers.SetCharacterProperties("PLAYER", CharacterObject.PlayerCharacter, parent);
          parent.SetTextVariable("GOLD_ICON", "{=!}<img src=\"General\\Icons\\Coin@2x\" extend=\"8\">");
          parent.SetTextVariable("REWARD", this.RewardGold);
          return parent;
        }
      }

      public override TextObject IssueLordSolutionAcceptByPlayer
      {
        get
        {
          return new TextObject("{=azHy8uwl}I will issue a decree to remove the restrictions on the sale of goods.");
        }
      }

      public override TextObject IssueLordSolutionResponseByIssueGiver
      {
        get
        {
          return new TextObject("{=hAyFpmxq}My {?PLAYER.GENDER}lady{?}lord{\\?}, that would be very good. The merchants won't like it but hard-working artisans like me will be grateful to you.");
        }
      }

      public override TextObject IssueLordSolutionCounterOfferExplanationByOtherNpc
      {
        get
        {
          return new TextObject("{=nbeCbTH6}My {?PLAYER.GENDER}lady{?}lord{\\?}, we heard that you wish to issue a decree permitting artisans to behave like merchants. This will undo an arrangement here that's worked for generations. Please reconsider this.");
        }
      }

      public override TextObject IssueLordSolutionCounterOfferBriefByOtherNpc
      {
        get
        {
          return new TextObject("{=KSeIOHDh}(One of the merchants in the town comes to talk as you are preparing to depart.)");
        }
      }

      public override TextObject IssueLordSolutionCounterOfferAcceptByPlayer
      {
        get => new TextObject("{=dpFFo2U2}I understand. I'll hold off on the decree, then.");
      }

      public override TextObject IssueLordSolutionCounterOfferAcceptResponseByOtherNpc
      {
        get
        {
          return new TextObject("{=6ZTNuF30}That's the right call. Thank you for listening to the voice of reason.");
        }
      }

      public override TextObject IssueLordSolutionCounterOfferDeclineByPlayer
      {
        get => new TextObject("{=K1J6Xqht}Sorry, I have to do it.");
      }

      public override TextObject IssueLordSolutionCounterOfferDeclineResponseByOtherNpc
      {
        get
        {
          return new TextObject("{=YjsRb88D}That's your right, my {?PLAYER.GENDER}lady{?}lord{\\?}. But if you can't get the support of the merchants here when you next need it, well, don't say no one said anything.");
        }
      }

      protected override TextObject LordSolutionStartLog
      {
        get
        {
          return new TextObject("{=FT9V47bd}You issued a decree to remove the restrictions on the sale of goods, as the artisans had requested.");
        }
      }

      protected override TextObject LordSolutionCounterOfferAcceptLog
      {
        get
        {
          TextObject parent = new TextObject("{=SpIn5pr4}After listening to the town merchants, you decided to keep the restrictions on the sale of goods. Your decision made the merchants happy but disappointed the {QUEST_GIVER.LINK}.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.IssueOwner.CharacterObject, parent);
          return parent;
        }
      }

      public override TextObject IssueQuestSolutionAcceptByPlayer
      {
        get
        {
          TextObject parent = new TextObject("{=ueUsg9OL}I can take your goods to {TARGET_HERO.LINK} in {TARGET_SETTLEMENT} myself.");
          parent.SetTextVariable("TARGET_SETTLEMENT", this._targetSettlement.EncyclopediaLinkWithName);
          StringHelpers.SetCharacterProperties("TARGET_HERO", this._targetHero.CharacterObject, parent);
          return parent;
        }
      }

      public override TextObject Title
      {
        get
        {
          TextObject title = new TextObject("{=qfClYYjK}Artisans can't sell their products in {ISSUE_GIVER_SETTLEMENT}");
          title.SetTextVariable("ISSUE_GIVER_SETTLEMENT", this.IssueSettlement.Name);
          return title;
        }
      }

      public override TextObject Description
      {
        get
        {
          TextObject description = new TextObject("{=3KpgHPlo}The laws of {ISSUE_GIVER_SETTLEMENT} dictate that artisans sell their goods at a fixed rate to the merchants in town. And now they complain the price set by the merchants is not fair.");
          description.SetTextVariable("ISSUE_GIVER_SETTLEMENT", this.IssueOwner.CurrentSettlement.Name);
          return description;
        }
      }

      public override TextObject IssueAsRumorInSettlement
      {
        get
        {
          TextObject parent = new TextObject("{=TuIyqMWG}The artisans and the merchants are at each other's throats right now. I bet {QUEST_GIVER.NAME} is planning something.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.IssueOwner.CharacterObject, parent);
          return parent;
        }
      }

      public override TextObject IssueAlternativeSolutionAcceptByPlayer
      {
        get
        {
          TextObject solutionAcceptByPlayer = new TextObject("{=srbMyPXl}You can have one of my companions and {REQUIRED_TROOP_AMOUNT} of my men to take your goods to {TARGET_TOWN}");
          solutionAcceptByPlayer.SetTextVariable("REQUIRED_TROOP_AMOUNT", this.GetTotalAlternativeSolutionNeededMenCount());
          solutionAcceptByPlayer.SetTextVariable("TARGET_TOWN", this._targetSettlement.EncyclopediaLinkWithName);
          return solutionAcceptByPlayer;
        }
      }

      public override TextObject IssueDiscussAlternativeSolution
      {
        get
        {
          TextObject alternativeSolution = new TextObject("{=GE4DqFyl}I am still waiting for news from {TARGET_SETTLEMENT}. Thanks again for sparing your men.");
          alternativeSolution.SetTextVariable("TARGET_SETTLEMENT", this._targetSettlement.EncyclopediaLinkWithName);
          return alternativeSolution;
        }
      }

      public override TextObject IssueAlternativeSolutionResponseByIssueGiver
      {
        get
        {
          TextObject parent = new TextObject("{=EnS6NwaH}Thank you my {?PLAYER.GENDER}lady{?}lord{\\?}. I am sure your men will take care of the problem.");
          StringHelpers.SetCharacterProperties("PLAYER", CharacterObject.PlayerCharacter, parent);
          return parent;
        }
      }

      public ArtisanCantSellProductsAtAFairPriceIssue(Hero issueOwner)
      {
        MBList<string> mbList = new MBList<string>();
        mbList.Add("olives");
        mbList.Add("clay");
        mbList.Add("flax");
        mbList.Add("grape");
        mbList.Add("wool");
        mbList.Add("hardwood");
        mbList.Add("hides");
        this._possibleDeliveryItems = mbList;
        // ISSUE: explicit constructor call
        base.\u002Ector(issueOwner, CampaignTime.DaysFromNow(30f));
        this._targetSettlement = ArtisanCantSellProductsAtAFairPriceIssueBehavior.SelectTargetSettlement(issueOwner);
        this._targetHero = this._targetSettlement.Notables.GetRandomElementWithPredicate<Hero>((Func<Hero, bool>) (x => x.CanHaveQuestsOrIssues()));
        this._rawMaterialsToBeDelivered = Campaign.Current.ObjectManager.GetObject<ItemObject>(this._possibleDeliveryItems.GetRandomElement<string>());
        this.CounterOfferHero = ArtisanCantSellProductsAtAFairPriceIssueBehavior.SelectCounterOfferHero(issueOwner);
      }

      protected override float GetIssueEffectAmountInternal(IssueEffect issueEffect)
      {
        return issueEffect == DefaultIssueEffects.SettlementProsperity || issueEffect == DefaultIssueEffects.IssueOwnerPower ? -0.2f : 0.0f;
      }

      public override (SkillObject, int) GetAlternativeSolutionSkill(Hero hero)
      {
        return (hero.GetSkillValue(DefaultSkills.Charm) >= hero.GetSkillValue(DefaultSkills.Trade) ? DefaultSkills.Charm : DefaultSkills.Trade, 120);
      }

      protected override void LordSolutionConsequenceWithAcceptCounterOffer()
      {
        foreach (Hero notable in (List<Hero>) this.IssueOwner.CurrentSettlement.Notables)
        {
          if (notable.IsMerchant)
            ChangeRelationAction.ApplyPlayerRelation(notable, (int) (2.0 * (double) this.IssueDifficultyMultiplier));
        }
        this.RelationshipChangeWithIssueOwner = (int) (-5.0 * (double) this.IssueDifficultyMultiplier);
        TraitLevelingHelper.OnIssueSolvedThroughBetrayal(this.IssueOwner, new Tuple<TraitObject, int>[1]
        {
          new Tuple<TraitObject, int>(DefaultTraits.Honor, MathF.Round(-50f * this.IssueDifficultyMultiplier))
        });
        this.ApplyFailureEffects();
      }

      protected override void LordSolutionConsequenceWithRefuseCounterOffer()
      {
        this.ApplyLordSolutionSuccessRewards();
      }

      public override bool LordSolutionCondition(out TextObject explanation)
      {
        if (this.IssueOwner.CurrentSettlement.OwnerClan == Clan.PlayerClan)
        {
          explanation = TextObject.Empty;
          return true;
        }
        explanation = new TextObject("{=9y0zpKUF}You need to be the owner of this settlement!");
        return false;
      }

      public override bool AlternativeSolutionCondition(out TextObject explanation)
      {
        explanation = TextObject.Empty;
        return QuestHelper.CheckRosterForAlternativeSolution(MobileParty.MainParty.MemberRoster, this.GetTotalAlternativeSolutionNeededMenCount(), ref explanation);
      }

      public override bool DoTroopsSatisfyAlternativeSolution(
        TroopRoster troopRoster,
        out TextObject explanation)
      {
        explanation = TextObject.Empty;
        return QuestHelper.CheckRosterForAlternativeSolution(troopRoster, this.GetTotalAlternativeSolutionNeededMenCount(), ref explanation);
      }

      protected override void AlternativeSolutionEndWithSuccessConsequence()
      {
        this.ApplySuccessRewards();
      }

      private void ApplySuccessRewards()
      {
        this.IssueOwner.AddPower(10f);
        this.RelationshipChangeWithIssueOwner = 5;
        foreach (Hero gainedRelationWith in this.IssueOwner.CurrentSettlement.Notables.Where<Hero>((Func<Hero, bool>) (x => x.IsMerchant)))
        {
          gainedRelationWith.AddPower((float) (int) (-10.0 * (double) this.IssueDifficultyMultiplier));
          ChangeRelationAction.ApplyPlayerRelation(gainedRelationWith, -10);
        }
        this.IssueOwner.CurrentSettlement.Town.Prosperity += 30f;
      }

      private void ApplyLordSolutionSuccessRewards()
      {
        this.IssueOwner.AddPower(10f);
        this.RelationshipChangeWithIssueOwner = 10;
        this.CounterOfferHero.AddPower(-10f);
        foreach (Hero notable in (List<Hero>) this.IssueOwner.CurrentSettlement.Notables)
        {
          if (notable.IsMerchant)
          {
            if (notable != this.CounterOfferHero)
              ChangeRelationAction.ApplyPlayerRelation(notable, -5);
            else
              ChangeRelationAction.ApplyPlayerRelation(notable, -10);
          }
        }
        this.IssueOwner.CurrentSettlement.Town.Prosperity += 3f;
      }

      private void ApplyFailureEffects()
      {
        this.IssueOwner.AddPower(-10f);
        foreach (Hero hero in this.IssueOwner.CurrentSettlement.Notables.Where<Hero>((Func<Hero, bool>) (x => x.IsMerchant)))
          hero.AddPower(3f);
        this.IssueOwner.CurrentSettlement.Town.Prosperity -= 20f;
      }

      protected override void OnGameLoad()
      {
      }

      protected override void HourlyTick()
      {
      }

      protected override QuestBase GenerateIssueQuest(string questId)
      {
        return (QuestBase) new ArtisanCantSellProductsAtAFairPriceIssueBehavior.ArtisanCantSellProductsAtAFairPriceIssueQuest(questId, this.IssueOwner, CampaignTime.DaysFromNow(18f), this._targetSettlement, this._rawMaterialsToBeDelivered, this.RawMaterialCountToBeDelivered, this.RewardGold, this._targetHero, this.CounterOfferHero);
      }

      public override IssueBase.IssueFrequency GetFrequency() => IssueBase.IssueFrequency.Common;

      protected override bool CanPlayerTakeQuestConditions(
        Hero issueGiver,
        out IssueBase.PreconditionFlags flags,
        out Hero relationHero,
        out SkillObject skill)
      {
        relationHero = (Hero) null;
        flags = IssueBase.PreconditionFlags.None;
        if ((double) issueGiver.GetRelationWithPlayer() < -10.0)
        {
          flags |= IssueBase.PreconditionFlags.Relation;
          relationHero = issueGiver;
        }
        relationHero = issueGiver;
        skill = (SkillObject) null;
        return flags == IssueBase.PreconditionFlags.None;
      }

      public override bool IssueStayAliveConditions()
      {
        return this.CounterOfferHero != null && this._targetHero.IsActive && this.CounterOfferHero.IsActive && this.CounterOfferHero.CurrentSettlement == this.IssueSettlement;
      }

      protected override void CompleteIssueWithTimedOutConsequences()
      {
      }
    }

    public class ArtisanCantSellProductsAtAFairPriceIssueQuest : QuestBase
    {
      [SaveableField(10)]
      private readonly ItemObject _rawMaterialsToBeDelivered;
      [SaveableField(20)]
      private readonly int _amountOfRawGoodsToBeDelivered;
      [SaveableField(30)]
      private readonly Settlement _targetSettlement;
      [SaveableField(40)]
      private int _deliveredRawGoods;
      [SaveableField(100)]
      private Hero _counterOfferHero;
      [SaveableField(60)]
      private Hero _targetHero;
      [SaveableField(70)]
      private bool _counterOfferGiven;
      [SaveableField(80)]
      private bool _counterOfferRefused;
      [SaveableField(90)]
      private int _rewardGold;
      [SaveableField(212)]
      private JournalLog _playerStartsQuestLog;

      internal static void AutoGeneratedStaticCollectObjectsArtisanCantSellProductsAtAFairPriceIssueQuest(
        object o,
        List<object> collectedObjects)
      {
        ((MBObjectBase) o).AutoGeneratedInstanceCollectObjects(collectedObjects);
      }

      protected override void AutoGeneratedInstanceCollectObjects(List<object> collectedObjects)
      {
        base.AutoGeneratedInstanceCollectObjects(collectedObjects);
        collectedObjects.Add((object) this._rawMaterialsToBeDelivered);
        collectedObjects.Add((object) this._targetSettlement);
        collectedObjects.Add((object) this._counterOfferHero);
        collectedObjects.Add((object) this._targetHero);
        collectedObjects.Add((object) this._playerStartsQuestLog);
      }

      internal static object AutoGeneratedGetMemberValue_rawMaterialsToBeDelivered(object o)
      {
        return (object) ((ArtisanCantSellProductsAtAFairPriceIssueBehavior.ArtisanCantSellProductsAtAFairPriceIssueQuest) o)._rawMaterialsToBeDelivered;
      }

      internal static object AutoGeneratedGetMemberValue_amountOfRawGoodsToBeDelivered(object o)
      {
        return (object) ((ArtisanCantSellProductsAtAFairPriceIssueBehavior.ArtisanCantSellProductsAtAFairPriceIssueQuest) o)._amountOfRawGoodsToBeDelivered;
      }

      internal static object AutoGeneratedGetMemberValue_targetSettlement(object o)
      {
        return (object) ((ArtisanCantSellProductsAtAFairPriceIssueBehavior.ArtisanCantSellProductsAtAFairPriceIssueQuest) o)._targetSettlement;
      }

      internal static object AutoGeneratedGetMemberValue_deliveredRawGoods(object o)
      {
        return (object) ((ArtisanCantSellProductsAtAFairPriceIssueBehavior.ArtisanCantSellProductsAtAFairPriceIssueQuest) o)._deliveredRawGoods;
      }

      internal static object AutoGeneratedGetMemberValue_counterOfferHero(object o)
      {
        return (object) ((ArtisanCantSellProductsAtAFairPriceIssueBehavior.ArtisanCantSellProductsAtAFairPriceIssueQuest) o)._counterOfferHero;
      }

      internal static object AutoGeneratedGetMemberValue_targetHero(object o)
      {
        return (object) ((ArtisanCantSellProductsAtAFairPriceIssueBehavior.ArtisanCantSellProductsAtAFairPriceIssueQuest) o)._targetHero;
      }

      internal static object AutoGeneratedGetMemberValue_counterOfferGiven(object o)
      {
        return (object) ((ArtisanCantSellProductsAtAFairPriceIssueBehavior.ArtisanCantSellProductsAtAFairPriceIssueQuest) o)._counterOfferGiven;
      }

      internal static object AutoGeneratedGetMemberValue_counterOfferRefused(object o)
      {
        return (object) ((ArtisanCantSellProductsAtAFairPriceIssueBehavior.ArtisanCantSellProductsAtAFairPriceIssueQuest) o)._counterOfferRefused;
      }

      internal static object AutoGeneratedGetMemberValue_rewardGold(object o)
      {
        return (object) ((ArtisanCantSellProductsAtAFairPriceIssueBehavior.ArtisanCantSellProductsAtAFairPriceIssueQuest) o)._rewardGold;
      }

      internal static object AutoGeneratedGetMemberValue_playerStartsQuestLog(object o)
      {
        return (object) ((ArtisanCantSellProductsAtAFairPriceIssueBehavior.ArtisanCantSellProductsAtAFairPriceIssueQuest) o)._playerStartsQuestLog;
      }

      public override bool IsRemainingTimeHidden => false;

      public override TextObject Title => new TextObject("{=sfW7oT9e}Artisan can't sell products");

      private TextObject _playerStartsQuestLogText
      {
        get
        {
          TextObject parent = new TextObject("{=N0E8gd5H}{QUEST_GIVER.LINK} an artisan from {QUEST_GIVER_SETTLEMENT} has complained to you about not being able to sell their goods at the price they want because of the unfair local laws. {?QUEST_GIVER.GENDER}She{?}He{\\?} will pay {REWARD_AMOUNT}{GOLD_ICON} for you to take the goods to another town. You agreed to take {?QUEST_GIVER.GENDER}her{?}his{\\?} goods to {TARGET_HERO.LINK} in {TARGET_SETTLEMENT}.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          StringHelpers.SetCharacterProperties("TARGET_HERO", this._targetHero.CharacterObject, parent);
          parent.SetTextVariable("QUEST_GIVER_SETTLEMENT", this.QuestGiver.CurrentSettlement.Name);
          parent.SetTextVariable("TARGET_SETTLEMENT", this._targetSettlement.EncyclopediaLinkWithName);
          parent.SetTextVariable("REWARD_AMOUNT", this.RewardGold);
          parent.SetTextVariable("GOLD_ICON", "{=!}<img src=\"General\\Icons\\Coin@2x\" extend=\"8\">");
          return parent;
        }
      }

      private TextObject _successQuestLogText
      {
        get
        {
          TextObject parent = new TextObject("{=7fr8QDYi}{QUEST_GIVER.LINK} sends {?QUEST_GIVER.GENDER}her{?}his{\\?} regards for a fine job done with the {REWARD}{GOLD_ICON} {?QUEST_GIVER.GENDER}she{?}he{\\?} promised.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          parent.SetTextVariable("REWARD", this._rewardGold);
          parent.SetTextVariable("GOLD_ICON", "{=!}<img src=\"General\\Icons\\Coin@2x\" extend=\"8\">");
          return parent;
        }
      }

      private TextObject _failQuestLogText
      {
        get
        {
          TextObject parent = new TextObject("{=um4UaneZ}You have failed to deliver {REQUESTED_AMOUNT} {.%}{?(REQUESTED_AMOUNT > 1)}{PLURAL(RAW_MATERIALS)}{?}{RAW_MATERIALS}{\\?}{.%} to {TARGET_SETTLEMENT} in time as {QUEST_GIVER.LINK} asked you.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          parent.SetTextVariable("REMAINING_AMOUNT", this._amountOfRawGoodsToBeDelivered - this._deliveredRawGoods);
          parent.SetTextVariable("REQUESTED_AMOUNT", this._amountOfRawGoodsToBeDelivered);
          parent.SetTextVariable("TARGET_SETTLEMENT", this._targetSettlement.EncyclopediaLinkWithName);
          parent.SetTextVariable("RAW_MATERIALS", this._rawMaterialsToBeDelivered.Name);
          return parent;
        }
      }

      private TextObject _failQuestLogCounterOfferText
      {
        get
        {
          TextObject parent = new TextObject("{=pskiLikd}After listening to the town merchants, you decided to keep the restrictions on the sale of goods. Your decision made the merchants happy but disappointed {QUEST_GIVER.LINK}.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject _onQuestCancelledDueToWarLogText
      {
        get
        {
          TextObject parent = new TextObject("{=vaUlAZba}Your clan is now at war with {QUEST_GIVER.LINK}. Your agreement with {QUEST_GIVER.LINK} was canceled.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject _playerDeclaredWarQuestLogText
      {
        get
        {
          TextObject parent = new TextObject("{=bqeWVVEE}Your actions have started a war with {QUEST_GIVER.LINK}'s faction. {?QUEST_GIVER.GENDER}She{?}He{\\?} cancels your agreement and the quest is a failure.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      public ArtisanCantSellProductsAtAFairPriceIssueQuest(
        string questId,
        Hero questGiver,
        CampaignTime duration,
        Settlement targetSettlement,
        ItemObject rawGoodsToBeDelivered,
        int amountOfRawGoodsToBeDelivered,
        int rewardGold,
        Hero targetHero,
        Hero counterOfferHero)
        : base(questId, questGiver, duration, rewardGold)
      {
        this._targetSettlement = targetSettlement;
        this._rawMaterialsToBeDelivered = rawGoodsToBeDelivered;
        this._amountOfRawGoodsToBeDelivered = amountOfRawGoodsToBeDelivered;
        this._deliveredRawGoods = 0;
        this._counterOfferHero = counterOfferHero;
        this._targetHero = targetHero;
        this._rewardGold = rewardGold;
        this.SetDialogs();
        this.InitializeQuestOnCreation();
      }

      protected override void InitializeQuestOnGameLoad()
      {
        this.SetDialogs();
        Campaign.Current.ConversationManager.AddDialogFlow(this.GetCounterOfferDialogFlow(), (object) this);
        Campaign.Current.ConversationManager.AddDialogFlow(this.GetDeliveryDialogFlow(), (object) this);
      }

      protected override void HourlyTick()
      {
      }

      protected override void SetDialogs()
      {
        this.OfferDialogFlow = DialogFlow.CreateDialogFlow("issue_classic_quest_start").NpcLine(new TextObject("{=7KshRCtM}Excellent. I'll have the goods delivered to you right away.[if:convo_nonchalant]")).Condition((ConversationSentence.OnConditionDelegate) (() => Hero.OneToOneConversationHero == this.QuestGiver)).Consequence(new ConversationSentence.OnConsequenceDelegate(this.QuestAcceptedConsequences)).CloseDialog();
        this.DiscussDialogFlow = DialogFlow.CreateDialogFlow("quest_discuss").NpcLine(new TextObject("{=6qKJ6Uzr}I believe the goods have been delivered to you.")).Condition((ConversationSentence.OnConditionDelegate) (() => Hero.OneToOneConversationHero == this.QuestGiver)).BeginPlayerOptions().PlayerOption(new TextObject("{=6ZCAQ1S9}Great. I will be heading out soon.")).NpcLine(new TextObject("{=3SBDbPjD}Good to hear that! Safe journeys.")).CloseDialog().PlayerOption(new TextObject("{=JOaD2BlP}In due time. Let's not be too hasty here.")).NpcLine(new TextObject("{=ppi6eVos}As you wish.")).CloseDialog().EndPlayerOptions().CloseDialog();
      }

      private void QuestAcceptedConsequences()
      {
        this.StartQuest();
        TextObject taskName = new TextObject("{=L700FNht}Delivered {RAW_MATERIAL}");
        taskName.SetTextVariable("RAW_MATERIAL", this._rawMaterialsToBeDelivered.Name);
        this._playerStartsQuestLog = this.AddDiscreteLog(this._playerStartsQuestLogText, taskName, this._deliveredRawGoods, this._amountOfRawGoodsToBeDelivered, hideInformation: true);
        PartyBase.MainParty.ItemRoster.AddToCounts(this._rawMaterialsToBeDelivered, this._amountOfRawGoodsToBeDelivered);
        this.AddTrackedObject((ITrackableCampaignObject) this._targetSettlement);
        this.AddTrackedObject((ITrackableCampaignObject) this._targetHero);
        Campaign.Current.ConversationManager.AddDialogFlow(this.GetCounterOfferDialogFlow(), (object) this);
        Campaign.Current.ConversationManager.AddDialogFlow(this.GetDeliveryDialogFlow(), (object) this);
      }

      private int GetAvailableRequestedItemCountOnPlayer(ItemObject item)
      {
        return PartyBase.MainParty.ItemRoster.GetItemNumber(item);
      }

      private void BeforeGameMenuOpened(MenuCallbackArgs args)
      {
        if (this._counterOfferGiven || this._counterOfferHero == null || Campaign.Current.GameMenuManager.NextLocation != null || !(GameStateManager.Current.ActiveState is MapState))
          return;
        CampaignMapConversation.OpenConversation(new ConversationCharacterData(CharacterObject.PlayerCharacter), new ConversationCharacterData(this._counterOfferHero.CharacterObject));
        this._counterOfferGiven = true;
      }

      private DialogFlow GetCounterOfferDialogFlow()
      {
        if (this.QuestGiver.CurrentSettlement.Owner != Hero.MainHero)
        {
          TextObject textObject = new TextObject("{=riYecgOn}We have heard rumors that you have purchased goods from {QUEST_GIVER.NAME}. Well, our laws require that only merchants resident in the city can buy goods directly from the artisans.[if:convo_annoyed][ib:hip]");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, textObject);
          TextObject npcText = new TextObject("{=5AvvGkk4}I'm sure what you did was an honest mistake, but there are laws. Hand over the contraband to me, and this will be the end of it.");
          if (this._counterOfferHero.CharacterObject.GetPersona() == DefaultTraits.PersonaCurt)
            npcText = new TextObject("{=PyjCZGlG}This town has laws about unauthorized trade. Turn over the goods to me now.");
          return DialogFlow.CreateDialogFlow("start", 125).NpcLine(new TextObject("{=KSeIOHDh}(One of the merchants in the town comes to talk as you are preparing to depart.)")).Condition((ConversationSentence.OnConditionDelegate) (() => this._counterOfferHero == Hero.OneToOneConversationHero && !this._counterOfferRefused)).NpcLine(textObject).NpcLine(npcText).BeginPlayerOptions().PlayerOption(new TextObject("{=mWLA9sfT}I don't want to break the law. You can take the goods.")).NpcLine(new TextObject("{=xeboujso}That's the right call. You seem a responsible type.[if:convo_nonchalant]")).Consequence((ConversationSentence.OnConsequenceDelegate) (() => Campaign.Current.ConversationManager.ConversationEndOneShot += new Action(this.QuestFailedWithRefusal))).CloseDialog().PlayerOption(new TextObject("{=fe0uGUZb}That's just robbery under the cover of law. I'm not giving you anything.")).NpcLine(new TextObject("{=U9z7rvX5}Respectfully, you're making a big mistake and I think you're going to regret it.[if:convo_furious]")).Consequence((ConversationSentence.OnConsequenceDelegate) (() => Campaign.Current.ConversationManager.ConversationEndOneShot += new Action(this.RefuseCounterOfferConsequences))).CloseDialog().EndPlayerOptions();
        }
        TextObject textObject1 = new TextObject("{=DidANRmb}My {?PLAYER.GENDER}lady{?}lord{\\?}, we have heard rumors that you have purchased goods from {QUEST_GIVER.NAME}.[ib:demure] Surely this cannot be true. Our laws require that only merchants resident in the city can buy goods directly from the artisans.");
        StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, textObject1);
        TextObject npcText1 = new TextObject("{=bbz2eyAO}Perhaps, my {?PLAYER.GENDER}lady{?}lord{\\?}, it was a mistake? If you were to relinquish the goods, it would avoid a situation that might appear, well, a bit unseemly.");
        return DialogFlow.CreateDialogFlow("start", 125).NpcLine(new TextObject("{=KSeIOHDh}(One of the merchants in the town comes to talk as you are preparing to depart.)")).Condition((ConversationSentence.OnConditionDelegate) (() => this._counterOfferHero == Hero.OneToOneConversationHero && !this._counterOfferRefused)).NpcLine(textObject1).NpcLine(npcText1).BeginPlayerOptions().PlayerOption(new TextObject("{=EKvwhGtE}I suppose the laws of this town bind me as well. You can take the goods.")).NpcLine(new TextObject("{=dSy9Hawq}A just decision, my {?PLAYER.GENDER}lady{?}lord{\\?}.")).Consequence((ConversationSentence.OnConsequenceDelegate) (() => Campaign.Current.ConversationManager.ConversationEndOneShot += new Action(this.QuestFailedWithRefusal))).CloseDialog().PlayerOption(new TextObject("{=IUCkbHkT}I decide how the law here is applied, merchant.")).NpcLine(new TextObject("{=RYOuDxdu}Respectfully, my {?PLAYER.GENDER}lady{?}lord{\\?}, I must protest this. But of course you are free to do what you will.")).Consequence((ConversationSentence.OnConsequenceDelegate) (() => Campaign.Current.ConversationManager.ConversationEndOneShot += new Action(this.RefuseCounterOfferConsequences))).CloseDialog().EndPlayerOptions();
      }

      private DialogFlow GetDeliveryDialogFlow()
      {
        TextObject textObject1 = new TextObject("{=8nwZXNTk}About the task {QUEST_GIVER.LINK} gave me...");
        StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, textObject1);
        TextObject textObject2 = new TextObject("{=mr7SgjAq}Yes... {QUEST_GIVER.LINK} sent word to us. We are expecting the {.%}{RAW_MATERIALS}{.%} that {?QUEST_GIVER.GENDER}she{?}he{\\?} had.");
        StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, textObject2);
        StringHelpers.SetCharacterProperties("PLAYER", CharacterObject.PlayerCharacter, textObject2);
        textObject2.SetTextVariable("RAW_MATERIALS", this._rawMaterialsToBeDelivered.Name);
        TextObject npcSecondLine = new TextObject("{=g7hZw8LI}Have you brought {REQUESTED_AMOUNT} {.%}{?(REQUESTED_AMOUNT > 1)}{PLURAL(RAW_MATERIALS)}{?}{RAW_MATERIALS}{\\?}{.%}? I have a fat purse of {REWARD}{GOLD_ICON} for you as promised.");
        npcSecondLine.SetTextVariable("GOLD_ICON", "{=!}<img src=\"General\\Icons\\Coin@2x\" extend=\"8\">");
        npcSecondLine.SetTextVariable("REWARD", this._rewardGold);
        npcSecondLine.SetTextVariable("REQUESTED_AMOUNT", this._amountOfRawGoodsToBeDelivered - this._deliveredRawGoods);
        npcSecondLine.SetTextVariable("RAW_MATERIALS", this._rawMaterialsToBeDelivered.Name);
        TextObject text1 = new TextObject("{=jidYZW2s}Most of the goods are here, but I lost some of them along the way. I have {AVAILABLE_AMOUNT} with me.");
        TextObject textObject3 = new TextObject("{=bPcO3Km2}Yes, things come up, but my agreement with {QUEST_GIVER.LINK} was for a fixed amount of goods. I don't want to negotiate a new deal. Please come back when you can get the full amount.[if:convo_nervous2][ib:closed]");
        StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, textObject3);
        TextObject playerDeliverItemsFully = new TextObject("{=yKz5e5H4}Yes. I have the goods right here. I brought {REQUESTED_AMOUNT} {.%}{?(REQUESTED_AMOUNT > 1)}{PLURAL(RAW_MATERIALS)}{?}{RAW_MATERIALS}{\\?}{.%} as we agreed.");
        playerDeliverItemsFully.SetTextVariable("REQUESTED_AMOUNT", this._amountOfRawGoodsToBeDelivered - this._deliveredRawGoods);
        playerDeliverItemsFully.SetTextVariable("RAW_MATERIALS", this._rawMaterialsToBeDelivered.Name);
        TextObject textObject4 = new TextObject("{=S60sDU3j}Very good! Here is your money. Thank you.[if:convo_grateful]");
        StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, textObject4);
        TextObject text2 = new TextObject("{=4uKTfTg9}Sorry. I don't have anything for you this time.");
        TextObject npcText = new TextObject("{=JTfaqKyX}Well, try to bring it soon.[if:convo_thinking][ib:closed]");
        TextObject text3 = new TextObject("{=GVJS9ewr}You know, these goods are worth more to me than what you'll paying. I will keep them.");
        TextObject textObject5 = new TextObject("{=kWZ3cskl}What? That's a breach of contract. {QUEST_GIVER.LINK} will certainly hear about this...[if:convo_grave][ib:aggressive]");
        StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, textObject5);
        return DialogFlow.CreateDialogFlow("hero_main_options", 125).PlayerLine(textObject1).Condition((ConversationSentence.OnConditionDelegate) (() =>
        {
          if (this._deliveredRawGoods > 0)
          {
            npcSecondLine.SetTextVariable("REQUESTED_AMOUNT", this._amountOfRawGoodsToBeDelivered - this._deliveredRawGoods);
            playerDeliverItemsFully.SetTextVariable("REQUESTED_AMOUNT", this._amountOfRawGoodsToBeDelivered - this._deliveredRawGoods);
          }
          return Settlement.CurrentSettlement == this._targetSettlement && CharacterObject.OneToOneConversationCharacter.IsHero && CharacterObject.OneToOneConversationCharacter.HeroObject == this._targetHero;
        })).NpcLine(textObject2).NpcLine(npcSecondLine).BeginPlayerOptions().PlayerOption(text1).Condition((ConversationSentence.OnConditionDelegate) (() =>
        {
          int itemCountOnPlayer = this.GetAvailableRequestedItemCountOnPlayer(this._rawMaterialsToBeDelivered);
          int num = this._amountOfRawGoodsToBeDelivered - this._deliveredRawGoods;
          Campaign.Current.ConversationManager.GetCurrentDialogLine().SetTextVariable("AVAILABLE_AMOUNT", itemCountOnPlayer);
          return itemCountOnPlayer < num && itemCountOnPlayer != 0;
        })).NpcLine(textObject3).Consequence(new ConversationSentence.OnConsequenceDelegate(this.DeliverItemsPartiallyOnConsequence)).CloseDialog().PlayerOption(playerDeliverItemsFully).Condition((ConversationSentence.OnConditionDelegate) (() =>
        {
          int itemCountOnPlayer = this.GetAvailableRequestedItemCountOnPlayer(this._rawMaterialsToBeDelivered);
          int variable = this._amountOfRawGoodsToBeDelivered - this._deliveredRawGoods;
          Campaign.Current.ConversationManager.GetCurrentDialogLine().SetTextVariable("REQUESTED_AMOUNT", this._amountOfRawGoodsToBeDelivered - this._deliveredRawGoods);
          Campaign.Current.ConversationManager.GetCurrentDialogLine().SetTextVariable("AVAILABLE_AMOUNT", variable);
          return itemCountOnPlayer >= variable && itemCountOnPlayer != 0;
        })).NpcLine(textObject4).Consequence(new ConversationSentence.OnConsequenceDelegate(this.DeliverItemsFullyOnConsequence)).CloseDialog().PlayerOption(text3).NpcLine(textObject5).Consequence(new ConversationSentence.OnConsequenceDelegate(this.DeliverItemsRejectOnConsequence)).CloseDialog().PlayerOption(text2).NpcLine(npcText).CloseDialog().EndPlayerOptions().CloseDialog();
      }

      private void DeliverItemsRejectOnConsequence()
      {
        TextObject textObject = new TextObject("{=yoiOIuI9}You refused to hand over the items. {QUEST_GIVER.LINK} must be furious.");
        StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, textObject);
        this.RelationshipChangeWithQuestGiver = -20;
        this.CompleteQuestWithFail(textObject);
        ChangeRelationAction.ApplyPlayerRelation(this._targetHero, -15);
      }

      private void DeliverItemsPartiallyOnConsequence()
      {
        int itemCountOnPlayer = this.GetAvailableRequestedItemCountOnPlayer(this._rawMaterialsToBeDelivered);
        this._deliveredRawGoods += itemCountOnPlayer;
        PartyBase.MainParty.ItemRoster.AddToCounts(this._rawMaterialsToBeDelivered, -itemCountOnPlayer);
        this.UpdateQuestTaskStage(this._playerStartsQuestLog, this._deliveredRawGoods);
        int variable = this._amountOfRawGoodsToBeDelivered - this._deliveredRawGoods;
        TextObject textObject = new TextObject("{=ffoqz6yP}You have delivered {DELIVERED_ITEM_COUNT} units of goods from {QUEST_GIVER.NAME}.");
        textObject.SetTextVariable("DELIVERED_ITEM_COUNT", itemCountOnPlayer);
        StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, textObject);
        MBInformationManager.AddQuickInformation(textObject);
        TextObject message = new TextObject("{=3zdK4sm2}You have to bring in amount {REQUIRED_AMOUNT} more to fulfill your end of the deal.");
        message.SetTextVariable("REQUIRED_AMOUNT", variable);
        MBInformationManager.AddQuickInformation(message);
      }

      private void DeliverItemsFullyOnConsequence()
      {
        int num = this._amountOfRawGoodsToBeDelivered - this._deliveredRawGoods;
        this._deliveredRawGoods = this._amountOfRawGoodsToBeDelivered;
        PartyBase.MainParty.ItemRoster.AddToCounts(this._rawMaterialsToBeDelivered, -num);
        this.UpdateQuestTaskStage(this._playerStartsQuestLog, this._deliveredRawGoods);
        TextObject textObject = new TextObject("{=WSLHfiwg}You have delivered the goods from {QUEST_GIVER.NAME}.");
        StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, textObject);
        MBInformationManager.AddQuickInformation(textObject);
        this.CompleteQuestWithSuccess();
      }

      private void QuestFailedWithRefusal()
      {
        foreach (Hero gainedRelationWith in this.QuestGiver.CurrentSettlement.Notables.Where<Hero>((Func<Hero, bool>) (x => x.IsMerchant)))
        {
          ChangeRelationAction.ApplyPlayerRelation(gainedRelationWith, 2);
          gainedRelationWith.AddPower(10f);
        }
        this.RelationshipChangeWithQuestGiver = -5;
        TraitLevelingHelper.OnIssueFailed(this.QuestGiver, new Tuple<TraitObject, int>[1]
        {
          new Tuple<TraitObject, int>(DefaultTraits.Honor, -50)
        });
        this.CompleteQuestWithFail(this._failQuestLogCounterOfferText);
        this.RemoveRequestedItemsFromPlayer();
      }

      private void RefuseCounterOfferConsequences()
      {
        if (this.QuestGiver.CurrentSettlement.Owner != Hero.MainHero)
          ChangeCrimeRatingAction.Apply(this.QuestGiver.CurrentSettlement.MapFaction, 5f);
        this._counterOfferHero.AddPower(-10f);
        this._counterOfferRefused = true;
      }

      protected override void RegisterEvents()
      {
        CampaignEvents.BeforeGameMenuOpenedEvent.AddNonSerializedListener((object) this, new Action<MenuCallbackArgs>(this.BeforeGameMenuOpened));
        CampaignEvents.HeroKilledEvent.AddNonSerializedListener((object) this, new Action<Hero, Hero, KillCharacterAction.KillCharacterActionDetail, bool>(this.OnHeroKilled));
        CampaignEvents.OnClanChangedKingdomEvent.AddNonSerializedListener((object) this, new Action<Clan, Kingdom, Kingdom, ChangeKingdomAction.ChangeKingdomActionDetail, bool>(this.OnClanChangedKingdom));
        CampaignEvents.WarDeclared.AddNonSerializedListener((object) this, new Action<IFaction, IFaction, DeclareWarAction.DeclareWarDetail>(this.OnWarDeclared));
      }

      public override void OnHeroCanHaveQuestOrIssueInfoIsRequested(Hero hero, ref bool result)
      {
        if (hero != this._targetHero)
          return;
        result = false;
      }

      private void OnClanChangedKingdom(
        Clan clan,
        Kingdom oldKingdom,
        Kingdom newKingdom,
        ChangeKingdomAction.ChangeKingdomActionDetail detail,
        bool showNotification = true)
      {
        if (!this.QuestGiver.CurrentSettlement.MapFaction.IsAtWarWith(Hero.MainHero.MapFaction))
          return;
        this.CompleteQuestWithCancel(this._onQuestCancelledDueToWarLogText);
      }

      private void OnWarDeclared(
        IFaction faction1,
        IFaction faction2,
        DeclareWarAction.DeclareWarDetail detail)
      {
        QuestHelper.CheckWarDeclarationAndFailOrCancelTheQuest((QuestBase) this, faction1, faction2, detail, this._playerDeclaredWarQuestLogText, this._onQuestCancelledDueToWarLogText);
      }

      private void OnHeroKilled(
        Hero victim,
        Hero killer,
        KillCharacterAction.KillCharacterActionDetail detail,
        bool showNotification)
      {
        if (victim == this._targetHero)
        {
          TextObject textObject = detail == KillCharacterAction.KillCharacterActionDetail.Lost ? this.TargetHeroDisappearedLogText : this.TargetHeroDiedLogText;
          StringHelpers.SetCharacterProperties("QUEST_TARGET", this._targetHero.CharacterObject, textObject);
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, textObject);
          this.AddLog(textObject);
          this.CompleteQuestWithCancel();
        }
        else
        {
          if (victim != this._counterOfferHero)
            return;
          this.CompleteQuestWithCancel();
        }
      }

      private void RemoveRequestedItemsFromPlayer()
      {
        int itemCountOnPlayer = this.GetAvailableRequestedItemCountOnPlayer(this._rawMaterialsToBeDelivered);
        int num = this._amountOfRawGoodsToBeDelivered - this._deliveredRawGoods;
        PartyBase.MainParty.ItemRoster.AddToCounts(this._rawMaterialsToBeDelivered, itemCountOnPlayer < num ? -itemCountOnPlayer : -num);
      }

      public override void OnFailed()
      {
        this.QuestGiver.AddPower(-10f);
        this.QuestGiver.CurrentSettlement.Town.Prosperity -= 20f;
        foreach (Hero hero in this.QuestGiver.CurrentSettlement.Notables.Where<Hero>((Func<Hero, bool>) (x => x.IsMerchant)))
          hero.AddPower(5f);
      }

      protected override void OnFinalize()
      {
      }

      protected override void AfterLoad()
      {
      }

      protected override void OnCompleteWithSuccess()
      {
        this.QuestGiver.AddPower(15f);
        this.RelationshipChangeWithQuestGiver = 10;
        TraitLevelingHelper.OnIssueSolvedThroughQuest(this.QuestGiver, new Tuple<TraitObject, int>[1]
        {
          new Tuple<TraitObject, int>(DefaultTraits.Honor, 50)
        });
        foreach (Hero gainedRelationWith in this.QuestGiver.CurrentSettlement.Notables.Where<Hero>((Func<Hero, bool>) (x => x.IsMerchant)))
        {
          gainedRelationWith.AddPower(-5f);
          ChangeRelationAction.ApplyPlayerRelation(gainedRelationWith, -5);
        }
        this.QuestGiver.CurrentSettlement.Town.Prosperity += 20f;
        this.AddLog(this._successQuestLogText);
        this.RemoveTrackedObject((ITrackableCampaignObject) this._targetSettlement);
        this.RemoveTrackedObject((ITrackableCampaignObject) this._targetHero);
        GiveGoldAction.ApplyBetweenCharacters((Hero) null, Hero.MainHero, this._rewardGold);
      }

      protected override void OnTimedOut()
      {
        this.OnFailed();
        this.RelationshipChangeWithQuestGiver = -5;
        this.AddLog(this._failQuestLogText);
      }

      public override void OnCanceled()
      {
      }
    }

    public class ArtisanCantSellProductsAtAFairPriceIssueTypeDefiner : SaveableTypeDefiner
    {
      public ArtisanCantSellProductsAtAFairPriceIssueTypeDefiner()
        : base(480000)
      {
      }

      protected override void DefineClassTypes()
      {
        this.AddClassDefinition(typeof (ArtisanCantSellProductsAtAFairPriceIssueBehavior.ArtisanCantSellProductsAtAFairPriceIssue), 1);
        this.AddClassDefinition(typeof (ArtisanCantSellProductsAtAFairPriceIssueBehavior.ArtisanCantSellProductsAtAFairPriceIssueQuest), 2);
      }
    }
  }
}
